import {
  axios
} from 'taro-axios'
import toast from '@/utils/toast';
import Taro from '@tarojs/taro';
import {
  login
} from '@/axios/api/user';
import {
  baseURL
} from '@/utils/config';
//---------
// 公共 base
// ------------
// 默认  基础路径

const request = axios.create();

request.defaults.baseURL = baseURL; //本地环境

let isRefreshing = false
//重试队列
let requests = []

// ------------
//  请求拦截器
// ------------
request.defaults.timeout = 10000;

request.interceptors.request.use(config => {
  // 设置请求头
  // 给请求头加token的字段,值为token
  config.headers.authorization = Taro.getStorageSync('token') ? 'Bearer ' + Taro.getStorageSync('token') : "";
  config.headers['Content-Type'] = 'application/json';
  return config
})
// ------------
//  响应拦截器
// ------------
request.interceptors.response.use(
  (response) => {
    const responseData = response.data;
    const {
      code,
      msg
    } = responseData;

    if (code === 200) {
      //
    } else if (code === 401 && !response.config.url.includes(login)) {
      //token过期
      const config = response.config
      if (!isRefreshing) {
        isRefreshing = true
        //调用刷新token的接口
        return refreshToken().then(res => {
          console.log('-------',res);
          const {
            token,
            userInfo
          } = res.data
          // 替换token
          request.setToken(token,userInfo)
          config.headers['authorization'] = `Bearer ${token}`;
          config.baseURL = baseURL;
          requests.forEach(cb => cb(token))
          requests = []
          return request(config)
        }).catch(err => {
          toast.error("授权失败");
          return Promise.reject(err)
        }).finally(() => {
          isRefreshing = false
        })
      } else {
        // 返回未执行 resolve 的 Promise
        return new Promise(resolve => {
          // 用函数形式将 resolve 存入，等待刷新后再执行
          requests.push((token) => {
            config.headers['authorization'] = `Bearer ${token}`;
            config.baseURL = baseURL;
            resolve(request(config))
          })
        })
      }
    } else if (code === 403 || code === 404) {
      toast.error('未登录');
      console.log('服务端错误：' + msg);
    } else {
      //
      toast.error('服务端错误')
      console.log('服务端错误：' + msg);
    }

    return responseData;
  },
  (error) => {
    // 对响应错误做点什么
    toast.error("服务端错误")
    return Promise.reject(error);
  },
);


request.setToken = (token,userInfo) => {
  request.defaults.headers['authorization'] = 'Bearer ' + token
  Taro.setStorageSync('token', token);
  Taro.setStorageSync('userInfo', userInfo);
  Taro.setStorageSync('datetime', new Date().toLocaleString());
}

const refreshToken = () => {
  const userInfo = Taro.getStorageSync('userInfo');
  return new Promise((resolve, reject) => {
    if (userInfo) {
      Taro.login({
        success: ({
          code
        }) => {
          resolve(request.post(login, {
            code,
            userInfo
          }))
        }
      })
    } else {
      reject(false);
      // toast.error("授权失败");
    }
  })
}

//导出
export default request;
